home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16304 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: news1.interserv.net!news
  2. From: <102276.2374@compuserv.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: const member function
  5. Date: 10 Apr 1996 09:23:43 GMT
  6. Organization: InterServ News Service
  7. Message-ID: <4kfumv$1sp@lal.interserv.net>
  8. NNTP-Posting-Host: ad57-200.compuserve.com
  9. Content-Type: text/plain
  10. Content-length: 1196
  11. X-Newsreader: AIR Mosaic (32-bit) 4.00
  12.  
  13.  
  14. >class X 
  15. >{
  16. >public:   //  Public methods
  17. >   X( )           : _value( 0 ) { }
  18. >   X( int value ) : _value( value ) { }
  19. >
  20. >   int value( ) const { return _value; }
  21. >
  22. >private:  //  Private methods
  23. >
  24. >   int& value( ) { return _value; }
  25. >
  26. >private:  //  Private data members
  27. >   int _value;
  28. >};
  29. >
  30. >main( )
  31. >{
  32. >   X t1( 1 );
  33. >   const X t2( 2 );
  34. >
  35. >   cout << t1.value() << endl;   //  This is an error
  36. >
  37. >   //  This line
  38. >   cout << t2.value() << endl;  //  Does this work?
  39. >}
  40. >
  41.  
  42. Sounds to me like your compilers are overloading the value() function
  43. based on the constness of whatever object your are using to invoke the
  44. method.
  45.  
  46. Obviously, the following declaration results in a non-const object :
  47.  
  48. X t1(1);
  49.  
  50. Since this is a non-const object, I believe that the compiler is attempting
  51. to invoke the non-const value() function in your class.
  52.  
  53. Since this function is declared as private, only members, derived classes
  54. and freinds would have access to it.
  55.  
  56. To prove this, you could try making istream::operator<<(int) a friend to see
  57. if the example code will compile.
  58.  
  59. Please let me know if this works.
  60.  
  61. David Visage 
  62. 102276.2374@compuserv.com
  63.  
  64.  
  65.